<template>
  <ElSelect
      v-model="selectedValue"
      filterable
      clearable
      :="$attrs"
      placeholder=""
  >
    <ElOption v-for="item in options" :key="item.val" :label="item.val" :value="item.name"/>
  </ElSelect>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElSelect, ElOption } from 'element-plus'
import { getdictIdList } from '../api'

interface Props {
  modelValue: string | null // 接收绑定值
  data: any // 其他数据对象
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string | null): void
}>()

const selectedValue = ref(props.modelValue)
const options = ref<Array<{ val: string, name: string }>>([])

// 监听 modelValue 外部变化
watch(() => props.modelValue, (newVal) => {
  selectedValue.value = newVal
})

// 监听 selectedValue 内部变化并同步到父组件
watch(selectedValue, (newVal) => {
  emit('update:modelValue', newVal)
})

// 获取选项
const getOptions = () => {
  const { wgwtfbyVal } = props.data
  if (wgwtfbyVal === '接待数据类') {
    getdictIdList({ parentId: 1016 }).then(res => {
      options.value = res
    })
  } else if (wgwtfbyVal === '接待内容类') {
    getdictIdList({ parentId: 1017 }).then(res => {
      options.value = res
    })
  } else if (wgwtfbyVal === '对接反馈类') {
    getdictIdList({ parentId: 1018 }).then(res => {
      options.value = res
    })
  } else if (wgwtfbyVal === '操作类') {
    getdictIdList({ parentId: 1019 }).then(res => {
      options.value = res
    })
  } else {
    options.value = []
  }
}

// 当 data.wgwtfbyVal 变化时，清空当前选择
watch(() => props.data.wgwtfbyVal, () => {
  selectedValue.value = null
  emit('update:modelValue', null)
  getOptions()
}, { deep: true })

getOptions()
</script>

